<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    action=""
    :auto-upload="false"
    :on-change="onChange"
    style='display:inline-block'
    :limit="1"
    :show-file-list='false'
  >
    <template v-slot>
      <el-button size="small" type="success">上传表格数据</el-button>
    </template>
  </el-upload>
</template>

<script lang='ts'>

import { defineComponent, ref } from '@vue/runtime-core'
import XLSX from 'xlsx'
export default defineComponent({
  name: 'Upload',
  setup () {
    const upload = ref()
    async function onChange (file) {
      console.log('file', file, upload.value)
      try {
        await readExcel(file.raw)
      } catch (error) {
        console.error('文件类型不正确', error)
      }
      upload.value.clearFiles()
    }

    function getHeaderRow (sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    }

    async function readExcel (file) {
      return new Promise((resolve) => {
        const headerKeys = ['name', 'unit', 'price']
        let index = 0
        const reader = new FileReader()
        reader.readAsBinaryString(file)
        reader.onload = ev => {
          const { result } = ev.target
          const workBook = XLSX.read(result, { type: 'binary' })
          const workSheet = workBook.Sheets[workBook.SheetNames[0]]

          const data = XLSX.utils.sheet_to_json(workSheet) as Array<any>
          const map = {}
          for (const key in data[0]) {
            if (index === headerKeys.length) {
              break
            }
            if (Object.prototype.hasOwnProperty.call(data[0], key)) {
              map[key] = headerKeys[index++]
            }
          }
          const excelData = data.slice(1).map(item => {
            const obj = {}
            for (const key in map) {
              obj[map[key]] = item[key]
            }
            return obj
          })
          console.log('header', map)
          console.log('excelData', excelData)
          resolve(excelData)
        }
      })
    }

    return {
      upload,
      onChange,
    }
  },
})
</script>

<style scoped lang="less">

</style>
